<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin\Sys;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use League\Flysystem\Filesystem;
use function Hyperf\Config\config;

#[Middlewares([AuthMiddleware::class])]
#[Controller]
class FileController extends AbstractController
{
    #[Inject]
    public Filesystem $filesystem;

    #[PostMapping(path: '/file/upload')]
    public function upload()
    {
        $file = $this->request->file('file');
        $mimeTypeArr = explode('/', $file->getMimeType());
        $fileType = $mimeTypeArr[0] ?? 'file';

        $tmpPath = $file->getRealPath();
        $signature = md5_file($tmpPath);
        $extension = $file->getExtension();
        $newFileName = $signature . '.' . $extension;

        $date = date('Ymd');
        $fileDir = "uploads/{$fileType}/{$date}";
        $filePath = "{$fileDir}/{$newFileName}";
        // 判断文件夹是否存在
        if (! is_dir('runtime/' . $fileDir)) {
            mkdir('runtime/' . $fileDir, 0777, true);
            chmod('runtime/' . $fileDir, 0777);
        }

        // $fileObj = $params['file'] = $this->request->file('file');
        // $filePath = $params['path'] = $this->request->input('path', '');
        // $fileName = $params['name'] = $this->request->input('name');
        // $ossFilePath = trim($filePath, '/');
        // $ext = strtolower($fileObj->getExtension());
        // $ossFileName = empty($fileName) ? Str::random(12) . date('His') : trim($fileName, '/');
        // $folderPath = 'uploads/'.trim($ossFilePath . '/' . $ossFileName . '.' . $ext, '/');
        $contents = file_get_contents($tmpPath);
        $this->filesystem->write($filePath, $contents);
        $dirve = config('file.default');
        return success(config('file.storage.' . $dirve . '.domain_url') . $filePath);
        // return success(['path' => $filePath, 'full_path' => config('file.storage.' . $dirve . '.domain_url') . $filePath]);
        // return ['path' => $filePath, 'full_path' => config('file.storage.' . $dirve . '.domain_url') . $filePath];
    }
}
